package com.spring.mvc.servlet.version_03;

import com.spring.mvc.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: WuPeng
 * @Date: 2021/6/7 11:53 上午
 */
public class IDispatcherServlet extends HttpServlet {

    //保存application.properties配置文件中的内容
    private Properties CONTEXT_CONFIG = new Properties();

    //保存扫描到的所有类名
    private List<String> CLASS_NAMES = new ArrayList<>();

    //IOC容器
    private Map<String, Object> IOC_CACHE = new HashMap<>();

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception, Detail: " + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        Handler handler = getHandler(req, resp);
        if (handler == null){
            resp.getWriter().write("404 Not Found !");
            return;
        }
        //所有方法的形参列表
        Class<?>[] paramsTypes = handler.getParamsTypes();

        Object[] paramValues = new Object[paramsTypes.length];

        Map<String, String[]> parameters = req.getParameterMap();
        for (Map.Entry<String, String[]> param : parameters.entrySet()){
            String value = Arrays.toString(param.getValue())
                    .replaceAll("\\[|\\]", "")
                    .replaceAll("\\s", ",");
            if (!handler.paramIndexMapping.containsKey(param.getKey())) continue;
            int index = handler.paramIndexMapping.get(param.getKey());
            paramValues[index] = convert(paramsTypes[index], value);
        }

        if (handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())){
            int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
        }
        if (handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())){
            int reqIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[reqIndex] = resp;
        }

        Object result = handler.method.invoke(handler.controller, paramValues);
        if (result == null || result instanceof Void) return;
        resp.getWriter().write(result.toString());
    }

    //URL穿过来的参数都是String类型的（HTTP是基于字符串协议的），所以只需要把String转换为对应类型就好
    private Object convert(Class<?> paramsType, String value) {
        if (Integer.class == paramsType)
            return Integer.valueOf(value);
        else if (Double.class == paramsType)
            return Double.valueOf(value);
        //继续添加以前类型（可用策略模式实现）
        return value;
    }

    private Handler getHandler(HttpServletRequest req, HttpServletResponse resp) {
        if (handlerMapping.isEmpty()) return null;
        //绝对路径
        String url = req.getRequestURI();
        //处理成相对路径
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");
        for (Handler handler : this.handlerMapping){
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) continue;
            return handler;
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //2、扫描相关的类
        doScanner(CONTEXT_CONFIG.getProperty("scanPackage"));
        //3、初始化扫描到的类，并且将它们放入到IOC容器中
        doInstance();
        //4、完成依赖注入
        doAutowired();
        //5、初始化HandlerMapping
        InitHandlerMapping();

        System.out.println("WuPeng's SpringFrameWork-v3 has been initialized");
    }

    private void InitHandlerMapping() {
        if (IOC_CACHE.isEmpty()) return;
        for (Map.Entry<String, Object> entry : IOC_CACHE.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if (clazz.isAnnotationPresent(IRequestMapping.class)){
                IRequestMapping requestMapping = clazz.getAnnotation(IRequestMapping.class);
                String base_path = requestMapping.value();
                Method[] methods = clazz.getMethods();
                for (Method method : methods){
                    if (method.isAnnotationPresent(IRequestMapping.class)){
                        IRequestMapping mapping = method.getAnnotation(IRequestMapping.class);

                        String regex = ("/" + base_path + "/" + mapping.value()).replaceAll("/+", "/");
                        Pattern pattern = Pattern.compile(regex);
                        this.handlerMapping.add(new Handler(pattern, method, entry.getValue()));
                        System.out.println("Mapped : " + pattern + "," + method);
                    }
                }
            }
        }
    }

    //自动注入
    private void doAutowired() {
        if (IOC_CACHE.isEmpty()){
            return;
        }
        for (Map.Entry<String, Object> entry: IOC_CACHE.entrySet()){
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields){
                if (!field.isAnnotationPresent(IAutowired.class)) continue;
                IAutowired iAutowired = field.getAnnotation(IAutowired.class);
                String beanName = iAutowired.value().trim();
                if("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);
                try {
                    //利用反射机制，动态给字段赋值
                    field.set(entry.getValue(), IOC_CACHE.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //IOC
    private void doInstance() {
        if (CLASS_NAMES.isEmpty()) return;
        try {
            for (String uri : CLASS_NAMES) {
                Class<?> clazz = Class.forName(uri);
                if (clazz.isAnnotationPresent(IController.class)){
                    Object instance = clazz.newInstance();
                    //默认使用首字母小写类名作为beanName
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    IOC_CACHE.put(beanName, instance);
                }
                else if (clazz.isAnnotationPresent(IService.class)) {
                    IService iService = clazz.getAnnotation(IService.class);
                    String beanName = iService.value();
                    if ("".equals(beanName.trim())){
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    IOC_CACHE.put(beanName, instance);
                    for (Class<?> cla : clazz.getInterfaces()){
                        if (IOC_CACHE.containsKey(cla.getName())){
                            throw new Exception("bean \"" + beanName + "\" is exists !");
                        }
                        //接口的类型直接当成key
                        IOC_CACHE.put(cla.getName(), instance);
                    }
                }
                else {
                    continue;
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    //扫描对应路径下的类文件，并加载到对应的容器中
    private void doScanner(String scan_path) {
        // 配置中的scanPackages 为包路径，需要转换为文件路径，就是把'.'替换为'/'
        URL url = this.getClass().getClassLoader().getResource("/" + scan_path.replaceAll("\\.", "/"));
        File class_files = new File(url.getFile());
        for (File file : class_files.listFiles()){
            if (file.isDirectory()){
                //递归扫描子文件夹下的文件
                doScanner(scan_path + "." +file.getName());
            }
            else {
                if (!file.getName().endsWith(".class")) continue;
                String className = (scan_path + "." +file.getName().replaceAll(".class", ""));
                CLASS_NAMES.add(className);
            }
        }
    }

    //读取配置文件，加载配置内容为Properties对象
    private void doLoadConfig(String contextConfigLocation) {
        //直接从类路径下找到spring主配置文件所在的路径，并将其读取出来放到Properties对象中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            CONTEXT_CONFIG.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //获取首字母小写的beanName（默认首字母一定是大写的）
    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    //保存controller中的url和method的关系
    public class Handler{
        private Pattern pattern;

        private Method method;

        private Object controller;

        private Class<?>[] paramsTypes;

        private Map<String, Integer> paramIndexMapping;

        public Handler(Pattern pattern, Method method, Object controller) {
            this.pattern = pattern;
            this.method = method;
            this.controller = controller;

            this.paramsTypes = method.getParameterTypes();
            this.paramIndexMapping = new HashMap<>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {
            //提取方法上加了注解的参数
            //拿到方法上的注解（一个二维数组，因为一个方法可以有多个注解、多个参数）
            Annotation[][] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length; i++) {
                for (Annotation annotation : pa[i]){
                    if (annotation instanceof IRequestParam){
                        String paramName = ((IRequestParam) annotation).value();
                        if (!"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }

            //获取方法中的HttpServletRequest、HttpServletResponse参数
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> type = paramsTypes[i];
                if (type == HttpServletRequest.class ||
                    type == HttpServletResponse.class){
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }

        public Pattern getPattern() {
            return pattern;
        }

        public Method getMethod() {
            return method;
        }

        public Object getController() {
            return controller;
        }

        public Class<?>[] getParamsTypes() {
            return paramsTypes;
        }
    }
}
